package com.example.project.activity.kaishi;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.VolleyError;
import com.example.project.R;
import com.example.project.activity.mingxi.MainActivity;
import com.example.project.bean.UserBean;
import com.example.project.db.DBManager;
import com.example.project.tool.SharePreferce;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.URLConnection;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
//登录页面
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private Button butLogin ; //登录按钮，注册按钮
    private EditText edtUser, edtPass; //账号框，密码框
    private ProgressDialog pd; //消息提示框
    private TextView tvMiMa,butReg; //忘记密码，网络设置，协议
    private String TAG = "LoginActivity";
    private boolean mima=false; //是否记住密码
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_login);
        initView();
    }

    private void initView() {


        butLogin=findViewById( R.id.bt_login );
        butLogin.setOnClickListener( this );
        edtUser=findViewById( R.id.et_login );
        edtPass=findViewById( R.id.et_pass );
        butReg=findViewById( R.id.bt_zc );
        butReg.setOnClickListener( this );
        pd = new ProgressDialog(this);
        tvMiMa=findViewById(R.id.tv_mima);
        tvMiMa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent( LoginActivity.this, AlterPassActivity.class );
                startActivity( intent );
            }
        });
        String name = SharePreferce.getInstance(LoginActivity.this).getString("userID");
        edtUser.setText(name);
        String pass = SharePreferce.getInstance(LoginActivity.this).getString("pass");
        edtPass.setText(pass);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()){
            case R.id.bt_login:
                String name = edtUser.getText().toString();
                String pass = edtPass.getText().toString();
                if(name.equals("") || pass.equals("")){
                    Toast.makeText(this,"你输入的为空",Toast.LENGTH_SHORT).show();
                    return;
                }else {
                    pd.setTitle("请稍等");
                    pd.setMessage("正在加载中......");
                    pd.show();
                    login(name,pass);
                }
                break;
            case R.id.bt_zc:
                intent=new Intent( LoginActivity.this, RegisterActivity.class );
                startActivity( intent );
                break;
            case R.id.tv_mima:
                intent=new Intent( LoginActivity.this, AlterPassActivity.class );
                startActivity( intent );
                break;
        }
    }

    //加载框(网络登录验证用户名，密码)
    public void login(final String name, final String pass) {
        final URLConnection urlConnection=new URLConnection();
        final String url= ConstantUtil.LOGINAPI;
        new Thread(new Runnable() {
            @Override
            public void run() {
//                sendEmail();
//                System.out.println("发送邮件");
                try {
                    Thread.sleep(1000); //延迟1秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Map paramer=new HashMap();
                paramer.put("username",name);
                paramer.put("password",pass);
                try {
                    String jsonString=urlConnection.net(url,paramer,"POST");
                    Message msg=Message.obtain();
                    msg.what=0;
                    msg.obj=jsonString;
                    myHanlder.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    //线程
    private Handler myHanlder=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            String strjson=(String) msg.obj;
            //处理数据
            try {
                handleLoginResult(strjson);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private void handleLoginResult(String json) throws JSONException {
        String state=null;
        JSONObject juser=null;
        System.out.println("json:"+json);
        if(json==null) {
            System.out.println("数据网站错误");
            Toast.makeText(this,"数据网站错误，请检查网站",Toast.LENGTH_SHORT).show();
            pd.dismiss();
            return;
        }
        if(json.equals("")){
            System.out.println("用户或密码错误");
            Toast.makeText(this,"用户或密码错误！",Toast.LENGTH_SHORT).show();
            pd.dismiss();
            return;
        }else {
            System.out.println("登陆成功");
            SharePreferce.getInstance(LoginActivity.this).setCache("mima",mima);
            Toast.makeText(this,"登陆成功",Toast.LENGTH_SHORT).show();
            state=json.substring(json.indexOf("{"),json.indexOf("}")+1);
            try {
                juser=new JSONObject(state);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            UserBean userBean =new UserBean(  );
            String name =juser.getString( "name" );
            int head=juser.getInt( "head" );
            int mainId=juser.getInt( "id" );
            userBean.setId(juser.getInt( "id" ));
            userBean.setName( juser.getString( "name" ) );
            userBean.setPass( juser.getString("pass") );
            userBean.setHead( juser.getInt("head") );
            userBean.setPhone( juser.getString("phone") );
            loginSuccess(userBean);
            Intent intent=new Intent( LoginActivity.this, MainActivity.class );
            startActivity( intent );
        }
        pd.dismiss();
    }

    //密码验证
    public void checkpass(){
        String name = edtUser.getText().toString();
        String pass = edtPass.getText().toString();

        Log.i("TAG",name+"_"+pass);
        DBManager dbManager=new DBManager();
        UserBean userBean =dbManager.login(name, pass); //验证登录信息
        if(userBean!=null){
            Log.i("TAG","登录成功");
            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent); //跳转
            int mainId=userBean.getId(); //用户Id
            int head=userBean.getHead();  //用户头像
            loginSuccess(userBean);
            pd.dismiss();
        }else{
            Log.i("TAG","登录失败");
            Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
            pd.dismiss();
        }
    }

    //将账号传给登录界面上
    private void loginSuccess(UserBean userBean) {
        SharePreferce.getInstance(LoginActivity.this).setCache("userID",userBean.getName());
        SharePreferce.getInstance( LoginActivity.this ).setCache( "mainId",userBean.getId() );
        SharePreferce.getInstance(LoginActivity.this).setCache("head",userBean.getHead());
        SharePreferce.getInstance(LoginActivity.this).setCache("pass",userBean.getPass());
    }


}